<template>
    <div class="e-form">
        <BillTop title="维保申请汇总详情" @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="维保明细" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="审核历史" name="auditHistory" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.maintenanceApplicationSummary" label-width="180px" :rules="rules">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="维保申请编号：">
                                            <span>{{ formData.maintenanceApplicationSummary.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="维保类型：" prop="type">
                                            <span>{{formData.maintenanceApplicationSummary.type?maintenanceType[formData.maintenanceApplicationSummary.type].label:''}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="是否签合同：">
                                            <el-checkbox v-model="formData.maintenanceApplicationSummary.isContract" disabled></el-checkbox>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12" >
                                        <el-form-item label="传输财务共享：" v-if="!formData.maintenanceApplicationSummary.isContract">
                                            <span :class="isFontColor ? 'redFont' : 'greenFont'">{{shareLable(formData.maintenanceApplicationSummary.share)}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="申请日期：" prop="billDate">
                                            <span>{{ formData.maintenanceApplicationSummary.billDate }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="申请人：">
                                            <span>{{ formData.maintenanceApplicationSummary.applicant }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                <el-col :span="12">
                                        <el-form-item label="费用合计：">
                                            <span>{{ formData.maintenanceApplicationSummary.maintenanceFee }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                        <span>{{ formData.maintenanceApplicationSummary.state !== '' ? statusLable(formData.maintenanceApplicationSummary.state) :'' }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="机构：">
                                            <span> {{formData.maintenanceApplicationSummary.orgName}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="state === 5">
                                        <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{ formData.maintenanceApplicationSummary.nullifyCreator }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{formData.maintenanceApplicationSummary.nullifyReason }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                formData.maintenanceApplicationSummary.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                        <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                formData.maintenanceApplicationSummary.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">维保明细</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="handoverDtlListCopy"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                v-sortTable="{ 'tableData': handoverDtlListCopy, '_this': this, 'ref': 'planTable' }"
                            >
                                <el-table-column  fixed type="index" label="序号" width="80" align="center">
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentNo"
                                    label="设备编号"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    label="设备名称"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="categoryName"
                                    label="设备类别"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="manufacturer"
                                    label="生产厂商"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="accumulate"
                                    label="累计使用数"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="维保费用（元）"
                                    prop="maintenanceFee"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="maintenanceDetails"
                                    label="维保内容"
                                    width="180"
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" isView bucketName="facilitymanagement" />
                    </div>

                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                billType="3005"
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.maintenanceApplicationSummary.state" @exas="exas" :founderId="formData.maintenanceApplicationSummary.founderId" :isPrint="formData.maintenanceApplicationSummary.state === 2" />
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/dailyManagement.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/equipment/components/auditHistory/auditHistoryIndex'
import { hideLoading, showLoading, webprintReport } from '@/utils/common'
import {  getCurrentUnitInfo, history } from '@/api/equip/dailyManagementAudit.js'
import { exas } from '@/pages/equipment/components/auditHistory/equipCom.js'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            formData: {
                //基础信息
                'maintenanceApplicationSummary': {
                    'applicant': '',
                    'applicantId': '',
                    'billDate': '',
                    'billId': '',
                    'billNo': '',
                    'founderId': '',
                    'founderName': '',
                    'isContract': null,
                    'maintenanceFee': 0,
                    'nullifyCreated': '',
                    'nullifyCreator': '',
                    'nullifyCreatorId': '',
                    'nullifyDescription': '',
                    'nullifyReason': '',
                    'orgId': '',
                    'orgName': '',
                    'share': 0,
                    'state': 0,
                    'type': '',
                    'workId': ''
                },
            },
            rules: {
                billDate: [
                    { required: true, message: '请选择申请日期', trigger: 'change' },
                ],
                type: [
                    { required: true, message: '请选择维保类型', trigger: 'change'  },
                ],
            },
            isFontColor: true, //传输财务共享颜色  未传，返回修改 红色   财务共享审核中，已传 绿色
            billid: this.$route.query.billid,
            handoverDtlList: [], //明细表格
            handoverDtlListCopy: [],
            planSelect: [], //明细选择项
            auditHistoryTable: [], //审核历史
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //计划明细错误显示
            isErrorMsg: true, //是否提醒错误信息
            currentRow: {},
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 3005,
                'freeNextUnitIndex': null,
                'freeNextUser': '',
                'isPass': true,
                'isShareInAudit': true,
                'opinion': '',
                'orgId': '',
                'orgName': '',
                'userId': '',
                'workId': ''
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 3005,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            maintenanceType: state=>state.equip.equipData.maintenanceType, //维保类型
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state//传财务单据状态
                const obj = state.find(x=>x.value === param)
                return obj.label
            }
        },
        //传输财务共享
        shareLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.shareFrom
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        //当前单据状态
        state () {
            return this.formData.maintenanceApplicationSummary.state
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        },
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    created () {
        this.userId = localStorage.getItem('userId')
        this.getDicValue()
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'attach', 'auditHistory']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setMaintenanceType')//更新维保类型
        },
        //传输财务共享字体颜色  未传，返回修改 红色   财务共享审核中，已传 绿色
        shareFontColor () {
            if(this.formData.maintenanceApplicationSummary.share === 0 || this.formData.maintenanceApplicationSummary.share === 1) {
                this.isFontColor = true
            }else{
                this.isFontColor = false
            }
        },
        //初始化数据
        init () {
            showLoading()
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getAuditHistory(),
                this.getCurrentUnitInfo()
            ]).finally(() => {
                hideLoading()
            })
        },
        getInfo () {
            const params = {
                id: this.billid,
            }
            request.maintenanceApplicationBaseInfo(params).then(res=>{
                this.formData.maintenanceApplicationSummary = res.maintenanceApplicationSummary
                this.shareFontColor()
            })
        },
        getPlanList () {
            const params = {
                id: this.billid,
            }
            request.maintenanceApplicationPlanInfo(params).then(res=>{
                this.handoverDtlListCopy = []
                res.summaryDtlList.map(item=>{
                    this.handoverDtlListCopy.push(item)
                })
                this.handoverDtlList = res.summaryDtlList
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            history(this.auditParams).then(res=>{
                this.auditHistoryTable = res
            })
        },
        //获取状态按钮
        getCurrentUnitInfo () {
            getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //==========计划明细===============
        //判断当前状态是否已修改
        curStateChange (row) {
            this.currentRow = row
            if (row.maintenanceApplicationSummaryDtlId) {
                this.currentRow.changeType = 2
            }
        },
        //选择设备
        planListAdd () {
            let obj = {
                'accumulate': null,
                'billId': this.billid,
                'billNo': '',
                'categoryId': '',
                'categoryName': '',
                'changeType': 1,
                'equipmentId': '',
                'equipmentName': '',
                'equipmentNo': '',
                'id': '',
                'maintenanceApplicationSummaryDtlId': '',
                'maintenanceDetails': '',
                'maintenanceFee': null,
                'manufacturer': '',
                'specificationModel': ''
            }
            this.handoverDtlListCopy.push(obj)
            this.handoverDtlList.push(obj)
        },
        //单个明细表格删除
        handleDelete (row, $index) {
            this.clientPop('info', ' 确定要删除吗？数据删除后不可恢复，请谨慎操作。', ()=>{
                let length = this.errorMsg.length
                this.handoverDtlListCopy.splice($index, 1)
                if(row.maintenanceApplicationSummaryDtlId) {
                    this.$set(this.handoverDtlList[$index], 'changeType', -1)
                }else{
                    this.handoverDtlList.splice($index, 1)
                }
                if (length > 0 ) {
                    this.verifyTable()
                }
            })
        },
        //获取明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //删除明细列表
        deletePlanList () {
            const length = this.planSelect.length
            if(length === 0) {
                this.clientPop(
                    'info',
                    '你还未选择数据,请选择!',
                )
            }else{
                this.clientPop(
                    'info',
                    `已选择【${length}】条数据，确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。`,
                    this.delete
                )
            }
        },
        delete () {
            this.planSelect.filter(row=>{
                this.handoverDtlListCopy.map((x, index)=>{
                    if(row == x ) {
                        this.handoverDtlListCopy.splice(index, 1)
                    }
                })
                if(row.maintenanceApplicationSummaryDtlId) {
                    const index = this.handoverDtlList.findIndex(item=>{
                        return item.maintenanceApplicationSummaryDtlId == row.maintenanceApplicationSummaryDtlId
                    })
                    this.$set(this.handoverDtlList[index], 'changeType', -1)
                }else{
                    this.handoverDtlList.map((x, index)=>{
                        if(row == x ) {
                            this.handoverDtlList.splice(index, 1)
                        }
                    })
                }
                if (length > 0 ) {
                    this.verifyTable()
                }
                this.$refs.planTable.clearSelection()
            })
        },
        //计划明细非空验证
        verifyTable () {
            return  new Promise((resolve, reject)=>{
                this.errorMsg = []
                this.handoverDtlListCopy.forEach((item, index)=>{
                    if(item.changeType !== -1) {
                        if(item.maintenanceFee === null || item.maintenanceFee === '') {
                            let str = `请填写第 ${index + 1} 行的（维保费用（元））`
                            this.errorMsg.push(str)
                        }
                        if(item.maintenanceDetails === null || item.maintenanceDetails === '') {
                            let str = `请填写第 ${index + 1} 行的（维保内容）`
                            this.errorMsg.push(str)
                        }
                    }
                })
                if(this.errorMsg.length > 0) {
                    reject()
                }else{
                    resolve()
                }
            })
        },
        //==========保存基本信息、明细==========
        //更新基础信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.form.validate(valid => {
                    if(valid) {
                        request.maintenanceApplicationUpdate(this.formData).then(()=>{
                            resolve()
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                            this.scorllError()
                        })
                    }else{
                        reject()
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateDetailInfo () {
            return new Promise((resolve, reject)=>{
                this.verifyTable().then(()=>{
                    request.operationLogDtlUpdate(this.handoverDtlList).then(()=>{
                        resolve()
                    }).catch(err=>{
                        reject(err)
                        this.setError('planDetail')
                        this.scorllError()
                    })
                }).catch(err=>{
                    this.setError('planDetail')
                    reject(err)
                    this.scorllError()
                })
            })
        },
        //取消
        handleClose () {
            this.$router.replace('/maintenanceApplicationList')
        },
        // 审核相关操作
        async exas (arg) {
            const requestFn = ()=>{
                return []
            }
            exas(arg, this, requestFn, 2)
            if (arg === 'print') {
                const printData = async ()=>{
                    showLoading()
                    try{
                        const  params =  {
                            'reportTitle': '维修保养申请', //报表名
                            'orgName': this.formData.maintenanceApplicationSummary.orgName, //单据机构
                            'reportQRUri': '', //报表内容URI
                            'billNo': this.formData.maintenanceApplicationSummary.billId, //单据编码
                            'summaryInfoItems': [ //基本信息
                                {
                                    'label': '维保类型',
                                    'value': this.formData.maintenanceApplicationSummary.type ? this.maintenanceType[this.formData.maintenanceApplicationSummary.type].label : '',
                                    'isFullRow': false //是否占整行
                                },
                                {
                                    'label': '申请日期',
                                    'value': this.formData.maintenanceApplicationSummary.billDate,
                                    'isFullRow': false //是否占整行
                                },
                                // {
                                //     'label': '设备编号',
                                //     'value': this.formData.totalCost,
                                //     'isFullRow': false //是否占整行
                                // },
                                // {
                                //     'label': '设备名称',
                                //     'value': this.formData.billDate,
                                //     'isFullRow': false //是否占整行
                                // },
                                // {
                                //     'label': '规格型号',
                                //     'value': this.formData.number,
                                //     'isFullRow': false //是否占整行
                                // },
                                // {
                                //     'label': '累计使用次数',
                                //     'value': this.formData.currency,
                                //     'isFullRow': false //是否占整行
                                // },
                                // {
                                //     'label': '生产厂商',
                                //     'value': this.formData.leaseType ? this.leaseTypeList[this.formData.leaseType].label : '',
                                //     'isFullRow': false //是否占整行
                                // },
                                // {
                                //     'label': '维保内容',
                                //     'value': this.formData.remarks,
                                //     'isFullRow': true //是否占整行
                                // },
                            ],
                            'tables': [ //表格
                                {
                                    'tableTitle': '维保详情',
                                    'tableContent': {
                                        '序号': 'index',
                                        '设备编号': 'equipmentNo',
                                        '设备名称': 'equipmentName',
                                        '规格型号': 'specificationModel',
                                        '累计使用次数': 'accumulate',
                                        '生产厂商': 'manufacturer',
                                        '维保内容': 'maintenanceDetails',
                                    },
                                    'tableData': this.handoverDtlListCopy, //表格数据
                                },
                                {
                                    'tableTitle': '审核历史',
                                    'tableContent': {
                                        '审核级次': 'unitName',
                                        '审核人': 'assignUser',
                                        '审核岗位': 'userTitle',
                                        '审核时间': 'completeTime',
                                        '审核意见': 'opinion',
                                    },
                                    'tableData': this.auditHistoryTable, //表格数据
                                }
                            ],
                        }

                        hideLoading()
                        return params
                    }catch(err) {
                        console.log(err)
                        this.clientPop('err', '打印失败')
                        hideLoading()
                    }
                }
                const data = await printData()
                webprintReport(data)
            }
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}
</style>
